import os
import cv2
import numpy as np
from datetime import datetime


def get_video_info(video_path):
    """获取视频基本信息"""
    cap = cv2.VideoCapture(video_path)
    if not cap.isOpened():
        return None

    info = {
        'width': int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),
        'height': int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)),
        'fps': cap.get(cv2.CAP_PROP_FPS),
        'frame_count': int(cap.get(cv2.CAP_PROP_FRAME_COUNT)),
        'duration': int(cap.get(cv2.CAP_PROP_FRAME_COUNT) / cap.get(cv2.CAP_PROP_FPS) * 1000)  # 毫秒
    }

    cap.release()
    return info


def format_duration(ms):
    """格式化时长（毫秒）为可读字符串"""
    seconds = ms // 1000
    hours = seconds // 3600
    minutes = (seconds % 3600) // 60
    seconds = seconds % 60
    return f"{hours:02d}:{minutes:02d}:{seconds:02d}"


def format_size(size_bytes):
    """格式化文件大小为可读字符串"""
    for unit in ['B', 'KB', 'MB', 'GB']:
        if size_bytes < 1024:
            return f"{size_bytes:.1f}{unit}"
        size_bytes /= 1024
    return f"{size_bytes:.1f}TB"


def get_file_info(file_path):
    """获取文件信息"""
    if not os.path.exists(file_path):
        return None

    stat = os.stat(file_path)
    return {
        'size': stat.st_size,
        'created': datetime.fromtimestamp(stat.st_ctime),
        'modified': datetime.fromtimestamp(stat.st_mtime)
    }


def calculate_similarity(features1, features2):
    """计算两个特征向量的相似度"""
    if isinstance(features1, dict) and isinstance(features2, dict):
        # 计算直方图相似度
        hist_similarity = cv2.compareHist(features1['histogram'], features2['histogram'], cv2.HISTCMP_CORREL)

        # 计算边缘密度相似度
        edge_similarity = 1 - abs(features1['edge_density'] - features2['edge_density'])

        # 计算HSV直方图相似度
        hsv_similarity = cv2.compareHist(features1['hsv_histogram'], features2['hsv_histogram'], cv2.HISTCMP_CORREL)

        # 综合相似度
        return (hist_similarity + edge_similarity + hsv_similarity) / 3
    else:
        # 计算余弦相似度
        return np.dot(features1, features2) / (np.linalg.norm(features1) * np.linalg.norm(features2))


def create_directory(path):
    """创建目录（如果不存在）"""
    if not os.path.exists(path):
        os.makedirs(path)


def is_video_file(filename):
    """检查文件是否为视频文件"""
    video_extensions = [
        '.mp4', '.avi', '.mkv', '.mov', '.wmv', '.flv',
        '.webm', '.m4v', '.mpeg', '.mpg', '.3gp'
    ]
    return any(filename.lower().endswith(ext) for ext in video_extensions)


def get_video_files(directory):
    """获取目录中的所有视频文件"""
    video_files = []
    for root, _, files in os.walk(directory):
        for file in files:
            if is_video_file(file):
                video_files.append(os.path.join(root, file))
    return video_files


def p_hash(frame):
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    gray = cv2.resize(gray, (8, 8))
    dct = cv2.dct(np.float32(gray))
    dct_roi = dct[0:8, 0:8]
    avreage = np.mean(dct_roi)
    phash_01 = (dct_roi > avreage) + 0
    phash_list = phash_01.reshape(1, -1)[0].tolist()
    hash = ''.join([str(x) for x in phash_list])
    return hash


def hamming_distance(hash1,hash2):
    num = 0
    for index in range(len(hash1)):
        if hash1[index] != hash2[index]:
            num += 1
    return num


if __name__ == "__main__":
    cap = cv2.VideoCapture(r'E:\JacksonLee\video\skate\demo\001.mp4')
    ret, frame = cap.read()
    idx = 0
    while ret:
        begin = cv2.getTickCount()
        hash1 = p_hash(frame)
        if idx > 0:
            hash2 = p_hash(last_frame)
            dist = hamming_distance(hash2, hash1)
            diff = 1 - dist * 1.0 / 64.0
            end = cv2.getTickCount()
            deal_time = (end - begin) / cv2.getTickFrequency() * 1000
            print("deal time:", deal_time)
            concat_img = cv2.hconcat((frame, last_frame))
            if diff >= 0.55:
                wait_time = 1
            else:
                wait_time = 0
            cv2.putText(concat_img, str(int(diff * 100)), (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 0))
            # cv2.namedWindow("diff", cv2.WINDOW_NORMAL)
            cv2.imshow("diff", concat_img)
            cv2.waitKey(wait_time)
        idx += 1
        import copy
        last_frame = copy.deepcopy(frame)
        ret, frame = cap.read()